﻿namespace Basic.Repository.SqlSugar
{
    public class SugarContext
    {

        private static MutiDBOperate Connect => GetMainConnectionDb();
        private static string _connectionString = Connect.Connection;
        private static DbType _dbType = (DbType)Connect.DbType;
        public static string ConnId = Connect.ConnId;
        private SqlSugarScope _db;

        public static MutiDBOperate GetMainConnectionDb()
        {
            var mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs.Find(x => x.ConnId == MainDb.CurrentDbConnId);
            if (BaseDBConfig.MutiConnectionString.allDbs.Count > 0)
            {
                if (mainConnetctDb == null)
                {
                    mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs[0];
                }
            }
            else
                throw new Exception("未配置主库");
            return mainConnetctDb;
        }

        public static string ConnectionString
        {
            get { return _connectionString; }
            set { _connectionString = value; }
        }

        public static DbType DbType
        {
            get { return _dbType; }
            set { _dbType = value; }
        }

        public SqlSugarScope Db
        {
            get { return _db; }
            private set { _db = value; }
        }

        public SugarContext(ISqlSugarClient sqlSugarClient)
        {
            if (string.IsNullOrEmpty(_connectionString))
                throw new ArgumentNullException("数据库连接字符串为空");
            _db = sqlSugarClient as SqlSugarScope;

        }

        #region 

        public static ISqlSugarClient GetDbClient(string connId)
        {
            var dbConf = BaseDBConfig.dbConfig.DataBase.Find(x => x.ConnId == connId);
            if (dbConf != null)
            {
                return new SqlSugarScope(new ConnectionConfig
                {
                    ConfigId = connId,
                    ConnectionString = dbConf.Connection,
                    DbType = dbConf.DbType,
                    MoreSettings = new ConnMoreSettings()
                    {
                        IsAutoRemoveDataCache = true
                    },
                });
            }
            return null;
        }

        #endregion


    }
}
